module Impressionizer

  class Engine < Rails::Engine

    initializer "impressionizer.load_app_instance_data" do |app|
      Impressionizer.setup do |config|
        config.app_root = app.root
      end
    end

    initializer "impressionizer.load_static_assets" do |app|
      app.middleware.use ::ActionDispatch::Static, "#{root}/public"
    end

    initializer 'impressionizer.extend_ar' do |app|
      ActiveRecord::Base.extend Impressionizer::Impressionable
    end

    initializer 'impressionizer.controller' do
      ActiveSupport.on_load(:action_controller) do
        include Impressionizer::ImpressionsController::InstanceMethods
        extend Impressionizer::ImpressionsController::ClassMethods
      end
    end

    initializer 'impressionizer.notification-subscriber' do
      ActiveSupport::Notifications.subscribe "process_action.action_controller" do |name, start, finish, id, payload|
        impression = Impressionizer::Impression.where(:request_id => id).first || Impressionizer::Impression.new

        impression.request_id = id
        impression.controller_name = payload[:controller]
        impression.action_name = payload[:action]
        impression.object_id = payload[:params][:id]
        impression.formats = payload[:formats]
        impression.method = payload[:method]
        impression.path = payload[:path]
        impression.status = payload[:status]
        impression.db_duration = payload[:view_runtime]
        impression.view_duration = payload[:db_runtime]
        impression.page_duration = (finish - start) * 1000

        impression.save
      end

      ActiveSupport::Notifications.subscribe "object.information"  do |name, start, finish, id, payload|
        impression = Impressionizer::Impression.where(:request_id => id).first || Impressionizer::Impression.new

        impression.request_id = id
        impression.impressionable_type = payload[:args][:impressionable_type]
        impression.impressionable_id = payload[:args][:impressionable_id]
        impression.session_hash = payload[:args][:session_hash]
        impression.referrer = payload[:args][:referrer]
        impression.ip_address = payload[:args][:ip_address]
        impression.user_id = payload[:args][:user_id]

        impression.save

        Rails.logger.debug "##### object.show - #{payload}"
      end
    end

  end

end